<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    />
    <div v-if="meta.indexOf('ActivityManagementAdd') > -1 || meta.indexOf('RegistrationExport') > -1" class="doumee_table_header">
      <el-button
        v-if="meta.indexOf('ActivityManagementAdd') > -1"
        v-preventReClick
        type="primary"
        @click="addActivty"
      >{{ $t('message.add') }}</el-button>
      <el-button v-if="meta.indexOf('RegistrationExport') > -1" :loading="exportLoading" type="primary" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="$t('message.hdname')"
        min-width="180"
        show-overflow-tooltip
        prop="name"
      >
        <template v-slot="scope">
          <span class="primaryColor pointer" @click="handleDetail(scope.row)">{{
            scope.row.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.hdhb')"
        width="120"
        prop="poster"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 60px;"
            fit="contain"
            :src="scope.row.poster"
            :preview-src-list="[scope.row.poster]"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.feiyon')"
        prop="price"
        min-width="80"
      />
      <el-table-column align="center" :label="$t('message.hdsj')" min-width="300">
        <template slot-scope="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.hddd')"
        prop="siteName"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column align="center" :label="$t('message.bmrsxz')" min-width="120">
        <template slot-scope="scope">
          {{ scope.row.signLimit> 0? scope.row.signLimit + $t('message.ren') : $t('message.bxz') }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.bmjzsj')"
        prop="applyEndTime"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.hdzt')"
        prop="theme"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.zbf')"
        prop="sponsor"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.cbf')"
        prop="organizer"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.bmrs')"
        prop="applyNum"
        min-width="120"
      />
      <el-table-column
        align="center"
        :label="$t('message.jljf')"
        prop="shareIntegral"
        min-width="120"
      />
      <el-table-column
        align="center"
        :label="$t('message.sort')"
        prop="sortNum"
        min-width="100"
      />
      <el-table-column
        align="center"
        :label="$t('message.createTime')"
        prop="createTime"
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.status')"
        prop="status"
        min-width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          {{
            scope.row.status == 0
              ? $t('message.dfb')
              : scope.row.status == 1
                ? $t('message.bmz')
                : scope.row.status == 2
                  ? $t('message.bmyjz')
                  : scope.row.status == 3
                    ? $t('message.jxz')
                    : scope.row.status == 4
                      ? $t('message.hdjs')
                      : $t('message.yqx')
          }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.caozuo')"
        :width="$i18n.locale === 'ZH'? 220 : 360"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <template v-if="scope.row.status == '0' || scope.row.status == '1' || scope.row.status == '2'">
              <el-button
                v-if="meta.indexOf('ActivityManagementEdit') > -1"
                v-preventReClick
                type="text"
                @click="toEdit(scope.row.id, scope.row.status)"
              >{{ $t('message.edit') }}</el-button>
            </template>
            <el-button
              v-if="meta.indexOf('ActivityManagementAdd') > -1"
              v-preventReClick
              type="text"
              @click="handleCopy(scope.row.id)"
            >{{ $t('message.copy') }}</el-button>
            <template v-if="scope.row.status == '0' || scope.row.status == '5'">
              <el-button
                v-if="meta.indexOf('ActivityManagementDel') > -1"
                v-preventReClick
                class="secondColor"
                type="text"
                @click="activityRemove(scope.row.id)"
              >{{ $t('message.del') }}</el-button>
            </template>
            <el-button
              v-if="
                scope.row.status == 0 &&
                  meta.indexOf('ActivityManagementPub') > -1
              "
              v-preventReClick
              type="text"
              @click="publish(scope.row.id)"
            >{{ $t('message.fb') }}</el-button>
            <el-button
              v-if="
                scope.row.status == 1 &&
                  meta.indexOf('ActivityManagementClose') > -1
              "
              v-preventReClick
              type="text"
              @click="activityClose(scope.row.id)"
            >{{ $t('message.qxhd') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog
      :title="activityTimeEdit ? $t('message.xghdksjs') : $t('message.xghdjzsj')"
      :visible.sync="showMotifyTime"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <el-form :model="activityInfo" label-width="auto">
        <el-form-item v-if="activityInfo.status == '1'" :label="$t('message.bmjzsj')">
          <el-date-picker
            v-model="activityInfo.applyEndTime"
            :picker-options="pickerOptions"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="$t('message.xzrq')"
          />
        </el-form-item>
        <el-form-item v-if="activityInfo.status == '2'" :label="$t('message.hdkssj')">
          <el-date-picker
            v-model="activityInfo.startTime"
            :picker-options="pickerOptions"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="$t('message.xzrq')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelMotify">{{ $t('message.qx') }}</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="confirmMotify"
        >{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <ActivityManagementDetail ref="ActivityManagementDetaillRef" />
  </div>
</template>

<script>
import {
  listActivity,
  activityPublish,
  activityClose,
  activityRemove,
  activityEditForApplyEndTime,
  activityExport,
  activityEditForStartTime
} from '@/api'
import { parseTime } from '@/utils/index'
import Pagination from '@/components/paginations'
import QueryForm from '@/components/QueryForm'
import ActivityManagementDetail from './activityManagementDetail.vue'
import store from '@/store'
export default {
  name: 'ActivityManagementList',
  components: {
    QueryForm,
    ActivityManagementDetail,
    Pagination
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      queryFormConfig: {
        formItems: [{
          filed: 'name',
          type: 'input',
          label: this.$t('message.hdmc'),
          clearable: true
        }, {
          filed: 'sponsor',
          type: 'input',
          label: this.$t('message.zbf'),
          clearable: true
        }, {
          filed: 'status',
          type: 'select',
          label: this.$t('message.status'),
          clearable: true,
          options: [
            { value: '0', label: this.$t('message.dfb') },
            { value: '1', label: this.$t('message.bmz') },
            { value: '2', label: this.$t('message.bmjz') },
            { value: '3', label: this.$t('message.hdjxz') },
            { value: '4', label: this.$t('message.yjs') },
            { value: '5', label: this.$t('message.yqx') }
          ]
        }],
        online: true
      },
      subLoading: false,
      meta: [],
      exportLoading: false,
      list: [],
      totalCount: 0,
      listLoading: true,
      activityTimeEdit: true,
      showMotifyTime: false,
      activityInfo: {},
      pagination: {
        page: 1,
        rows: 10
      },
      filters: {},
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
    if (this.$route.query.renovate && this.$route.query.renovate === '1') {
      this.getList()
    }
  },
  methods: {
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleDetail(row) {
      this.$refs.ActivityManagementDetaillRef.getCardList(row.id)
    },
    exportExcel() {
      this.exportLoading = true
      const { filters, pagination } = this
      activityExport({
        pagination,
        param: { ...filters, venueId: sessionStorage.getItem('venueId') }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            window.open(res.record.showUrl, '_blank')
          }
        })
        .catch(() => { this.exportLoading = false })
    },
    getList(page) {
      // 获取会员列表
      this.listLoading = true
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      listActivity({
        pagination,
        param: { ...filters, venueId: sessionStorage.getItem('venueId') }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.totalCount = res.totalCount
            if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
              this.getList(Math.ceil(res.totalCount / pagination.rows))
            }
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 编辑
    toEdit(id, status) {
      this.$router.push({ name: 'ActivityManagementAdd', query: { id: id, status }})
    },
    handleCopy(id) {
      this.$router.push({ name: 'ActivityManagementAdd', query: { id: id, type: 'copy' }})
    },
    addActivty() {
      this.$router.push({ name: 'ActivityManagementAdd' })
    },
    publish(activityId) {
      const that = this
      this.$confirm(this.$t('message.fbhdtcqr'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          activityPublish({ param: { activityId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.fbcg'))
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    activityClose(activityId) {
      const that = this
      this.$confirm(this.$t('message.qxhdtcqr'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          activityClose({ param: { activityId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.qxcg'))
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    activityRemove(activityId) {
      const that = this
      this.$confirm(this.$t('message.schdtcqr'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          activityRemove({ param: { activityId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.delcg'))
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    motifyActivtyTime(item) {
      this.activityInfo = { ... item }
      this.activityTimeEdit = true
      this.showMotifyTime = true
    },
    motifyApplyEndTime(item) {
      this.activityInfo = { ... item }
      this.activityTimeEdit = false
      this.showMotifyTime = true
    },
    cancelMotify() {
      this.showMotifyTime = false
    },
    confirmMotify() {
      // 修改报名截止日期
      var currentDate = new Date().getTime()
      var startTime = new Date(this.activityInfo.startTime).getTime()
      var endTime = new Date(this.activityInfo.endTime).getTime()
      var applyEndTime = new Date(this.activityInfo.applyEndTime).getTime()
      if (endTime < startTime) {
        this.$message.warning(this.$t('message.hdjsbnzyks'))
        return
      }
      if (endTime <= currentDate) {
        this.$message.warning(this.$t('message.hdjsbnzydq'))
        return
      }
      if (applyEndTime > startTime) {
        this.$message.warning(this.$t('message.bmjzbnwyhdks'))
        return
      }
      this.subLoading = true
      if (this.activityInfo.status === '1') {
        activityEditForApplyEndTime({
          param: {
            activityId: this.activityInfo.id,
            editTime: this.activityInfo.applyEndTime
          }
        })
          .then((res) => {
            if (res.errorCode === '000000') {
              this.subLoading = false
              this.showMotifyTime = false
              this.$message.success(this.$t('message.xgcg'))
              this.getList()
            }
          })
          .catch(() => {
            this.subLoading = false
          })
      } else if (this.activityInfo.status === '2') {
        // 修改活动开始日期
        activityEditForStartTime({
          param: {
            activityId: this.activityInfo.id,
            editTime: this.activityInfo.startTime
          }
        })
          .then((res) => {
            if (res.errorCode === '000000') {
              this.subLoading = false
              this.showMotifyTime = false
              this.$message.success(this.$t('message.xgcg'))
              this.getList()
            }
          })
          .catch(() => {
            this.subLoading = false
          })
      }
    },
    clear() {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>
